package com.huang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.base.BaseController;
import com.huang.dto.UserDto;
import com.huang.entity.Menu;
import com.huang.entity.Role;
import com.huang.resp.CommonResult;
import com.huang.service.MenuService;
import com.huang.service.RoleService;
import com.huang.util.OauthUtils;
import com.huang.validation.SaveGroupInterface;
import com.huang.validation.UpdateGroupInterface;
import com.huang.vo.LoginUserInfo;
import com.huang.vo.Pager;
import lombok.extern.log4j.Log4j2;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author han
 * @since 2022-05-29 19:05:06
 */
@Log4j2
@RestController
@RequestMapping("menu")
public class MenuController extends BaseController {

	@Resource
	private MenuService menuService;
	@Resource
	private RoleService roleService;

	@GetMapping("list")
	public CommonResult list(@RequestBody(required = false) Pager<Menu> pager) {
    	log.info("菜单管理列表入参：{}", pager);
		QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
		pager = (Pager<Menu>) parse(pager, queryWrapper);
		pager = menuService.page(pager, queryWrapper);
		return CommonResult.success(pager);
	}

	/**
	 * 根据角色查询该角色下的菜单列表
	 */
	@GetMapping("getMenuByToken")
	public CommonResult getMenuByToken() {
		LoginUserInfo currentUser = OauthUtils.getCurrentUser();
		List<Role> roleLis = roleService.findByUserId(currentUser.getUserId());
		List<String> roleIds = roleLis.stream().map(Role::getId).collect(Collectors.toList());
		List<Menu> menus = menuService.findByRoleIds(roleIds);
		return CommonResult.success(menus);
	}

	@PostMapping("add")
	public CommonResult add(@Validated(SaveGroupInterface.class) @RequestBody Menu menu) {
		boolean save = menuService.save(menu);
		return save ? CommonResult.success() : CommonResult.error("保存菜单失败");
	}

	@PostMapping("update")
	public CommonResult update(@Validated(UpdateGroupInterface.class) @RequestBody Menu menu) {
		boolean update = menuService.updateById(menu);
		return update ? CommonResult.success() : CommonResult.error("修改菜单失败");
	}

	@PostMapping("delete")
	public CommonResult delete(String ids) {
		boolean delete = menuService.removeByIds(Collections.singleton(ids));
		return delete ? CommonResult.success() : CommonResult.error("删除菜单失败");
	}

	@GetMapping("/test")
	public CommonResult test() {
		UserDto user = new UserDto();
		user.setRealName("不才陈某");
		user.setPhoneNumber("19796328206");
		user.setAddress("浙江省杭州市....");
		user.setIdCard("4333333333334334333");
		return CommonResult.success(user);
	}
}
